package com.heima.wemedia.service.impl;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.threadlocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    private List<String> imageType = Arrays.asList("png", "jpg", "jpeg", "gif", "bmp");

    /**
     * 素材上传
     *
     * @param file
     * @return
     */
    @Override
    @Transactional
    public ResponseResult upload(MultipartFile file) {

        //1.判断参数合法性

        //1.1 判断文件大小是否为空
        long size = file.getSize();
        if (file.isEmpty() || size == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文件内容不能为空");
        }

        //1.2 判断文件是否超限
        if (size > 2048 * 1024) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文件大小不能超过1M");
        }

        try {

            //1.2 判断文件类型是否图片
            String type = FileTypeUtil.getType(file.getInputStream());
            if (!imageType.contains(type)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文件类型必须是图片");
            }

            //2.拼接唯一文件名
            String fileNameFull = IdUtil.fastSimpleUUID() + "." + type;


            //3.上传文件到MinIO
            String url = fileStorageService.uploadImgFile("", fileNameFull, file.getInputStream());


            //4. 保存素材
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUrl(url);
            wmMaterial.setType((short) 0);
            wmMaterial.setIsCollection((short) 0);
            wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
            wmMaterial.setCreatedTime(new Date());
            this.save(wmMaterial);


            //5. 响应数据
            return ResponseResult.okResult(wmMaterial);

        } catch (IOException e) {
            e.printStackTrace();

            //6. 响应数据
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "上传出现问题");
        }
    }

    /**
     * 查询素材列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmMaterialDto dto) {
        //1.设置分页参数默认值
        dto.checkParam();

        //2.拼接查询条件
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId());
        lambdaQueryWrapper.eq(dto.getIsCollection() > 0, WmMaterial::getIsCollection, dto.getIsCollection());
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        //3.执行分页查询
        IPage<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        this.page(page, lambdaQueryWrapper);

        //4.封装分页响应结构
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), Long.valueOf(page.getTotal()).intValue());
        responseResult.setData(page.getRecords());

        return responseResult;
    }

    /**
     * 删除素材
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult del(Integer id) {
        WmMaterial wmMaterial = this.getById(id);
        if(wmMaterial==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "不存在无法删除");
        }

        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if(count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH, "被引用无法删除");
        }

        this.removeById(id);


        fileStorageService.delete(wmMaterial.getUrl());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 取消收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancel(Integer id) {
        Integer count = this.lambdaQuery().eq(WmMaterial::getId,id).count();
        if(count==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "不存在无法更新");
        }

        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setId(id);
        wmMaterial.setIsCollection((short)0);
        this.updateById(wmMaterial);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        Integer count = this.lambdaQuery().eq(WmMaterial::getId,id).count();
        if(count==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "不存在无法更新");
        }

        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setId(id);
        wmMaterial.setIsCollection((short)1);
        this.updateById(wmMaterial);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
